package com.cwt_taxi_xa.util;

import android.util.Log;

import com.cwt_taxi_xa.constants.Constants;

import java.io.File;
import java.io.FileOutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class CatchLogUtils {
    private static final String TAG = "FileUtil";

    private static final int SDCARD_LOG_FILE_SAVE_DAYS = 10; //SD卡日志文件保存时间
    private static SimpleDateFormat myLogSdf = new SimpleDateFormat("yyyy-MM-dd");
    static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
    static File outFile;
    static FileOutputStream fos;
    private static boolean catchLog = true;
    public synchronized static void saveLog(String str, Date day){
        if (!catchLog){
            return;
        }
        try{
            outFile = new File(Constants.LOG_PATH_DIR + myLogSdf.format(day)+ ".txt");
            if (!outFile.getParentFile().exists()){
                outFile.getParentFile().mkdir();
            }
            if (!outFile.exists()){
                outFile.createNewFile();
            }
            String lastLogTime = SPUtils.getParamString("logTime","");

            if (fos == null || lastLogTime != day.toString()){
                fos = new FileOutputStream(outFile,true);
            }
            AppLog.e("写出日志"+  "  ---------------------------" + str);
            fos.write((sdf.format(new Date())+  ":" + str).getBytes());
            fos.write("\n".getBytes());
            fos.flush();
            SPUtils.setParam("logTime",day.toString());
        }catch (Exception e){
            e.printStackTrace();
            fos = null;
        }

    }

    public static void stopLog(){
        catchLog = false;
    }

    public static void startLog(){
        catchLog = true;
    }
    /**
     * 删除内存下过期的日志
     */
    public static void deleteSDcardExpiredLog() {
        File file = new File(Constants.LOG_PATH_DIR);
        if (file.isDirectory()) {
            File[] allFiles = file.listFiles();
            for (File logFile : allFiles) {
                String fileName = logFile.getName();
                String createDateInfo = getFileNameWithoutExtension(fileName);
                if (canDeleteSDLog(createDateInfo)) {
                    logFile.delete();
                    Log.d(TAG, "delete expired log success,the log path is:"
                            + logFile.getAbsolutePath());

                }
            }
        }
    }

    /**
     * 判断sdcard上的日志文件是否可以删除
     * @param createDateStr
     * @return
     */
    public static boolean canDeleteSDLog(String createDateStr) {
        boolean canDel = false;
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_MONTH, -1 * SDCARD_LOG_FILE_SAVE_DAYS);//删除10天之前日志
        Date expiredDate = calendar.getTime();
        try {
            Date createDate = myLogSdf.parse(createDateStr);
            canDel = createDate.before(expiredDate);
        } catch (ParseException e) {
            Log.e(TAG, e.getMessage(), e);
            canDel = false;
        }
        return canDel;
    }

    /**
     * 去除文件的扩展类型（.log）
     * @param fileName
     * @return
     */
    private static String getFileNameWithoutExtension(String fileName){
        return fileName.substring(0, fileName.indexOf("."));
    }


}
